// [1432]改变一个整数能得到的最大差值
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn max_diff(num: i32) -> i32 {
        // 如果第一个数不为1，则直接替换为1
        // 否则从左到右替换第一个不为1且不为0的数为0获得
        let mut min = num;
        // 如果第一个数不为9，则直接替换为9
        // 否则从左到右替换第一个不为9的数为9获得
        let mut max = num;
        fn replace(s: &str, x: char, y: char) -> String {
            s.chars().map(|c| if c == x { y } else { c }).collect()
        }
        let mut max_num_str = num.to_string();
        for d in max_num_str.chars() {
            if d != '9' {
                max = replace(&max_num_str, d, '9').parse().unwrap();
                break;
            }
        }
        let mut min_num_str = num.to_string();
        for (i, d) in min_num_str.chars().enumerate() {
            if i == 0 {
                if d != '1' {
                    min = replace(&min_num_str, d, '1').parse().unwrap();
                    break;
                }
            } else {
                if d != '0' && d != min_num_str.chars().nth(0).unwrap() {
                    min = replace(&min_num_str, d, '0').parse().unwrap();
                    break;
                }
            }
        }
        max - min
    }
}
//leetcode submit region end(Prohibit modification and deletion)

#[test]
fn main() {
    let num = 555;
    assert_eq!(Solution::max_diff(num), 888);
    let num = 9;
    assert_eq!(Solution::max_diff(num), 8);
    let num = 123456;
    assert_eq!(Solution::max_diff(num), 820000);
    let num = 10000;
    assert_eq!(Solution::max_diff(num), 80000);
    let num = 9288;
    assert_eq!(Solution::max_diff(num), 8700);
}
